﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WaterRevenueMS.WebUI.Common;
using System.ComponentModel.Composition;
using WaterRevenueMS.WebUI.Extension.Filters;
using WaterRevenueMS.Domain.Common.Models;
using WaterRevenueMS.Domain.ViewModels.BasicSet.CompanySet;
using WaterRevenueMS.Domain.ViewModels.BaseData;
using WaterRevenueMS.Componnent.Entities.BaseData;
using System.Linq.Expressions;
using WaterRevenueMS.WebUI.Extension.MvcHelper;
using WaterRevenueMS.Componnent.Common;
using WaterRevenueMS.Core.Service.BasicSet;
using WaterRevenueMS.Core.Service.BasicSet.Impl;
using WaterRevenueMS.Core.Service.BaseData;
using WaterRevenueMS.Core.Repository.BaseData;
using WaterRevenueMS.Domain.ViewModels.BaseData.MeterReader;

namespace WaterRevenueMS.WebUI.Controllers
{

    [Export]
    [PartCreationPolicy(CreationPolicy.NonShared)]
    public class MeterReaderController : AdminController
    {
        [Import]
        public ICompanySetService CompanySetService { get; set; }

        [Import]
        public IMeterReaderService MeterReaderService { get; set; }

        [AdminLayoutAttribute]
        public ActionResult Index()
        {
            var model = new MeterReaderModel();
            #region 单位信息
            var parentModuleData = CompanySetService.CompanySets.Where(t => t.IsDeleted == false)
            .Select(t => new MeterReaderModel
            {
                CompanyId = t.Id,
                CompanyName = t.Dan_WMC
            });
            foreach (var item in parentModuleData)
            {
                model.Search.CompanyItems.Add(new SelectListItem { Text = item.CompanyName, Value = item.CompanyId.ToString() });
            }
            #endregion

            return View(model);
        }
        [AdminPermission(PermissionCustomMode.Ignore)]
        public ActionResult List(DataTableParameter param)
        {
            int total = MeterReaderService.MeterReaders.Count(t => t.IsDeleted == false);

            var expr = BuildSearchCriteria();

            var filterResult = MeterReaderService.MeterReaders.Where(expr).Select(t => new MeterReaderModel
            {
                id = t.Id,
                Chao_BYMC = t.Chao_BYMC,
                CompanyName = t.CompanySet != null ? t.CompanySet.Dan_WMC : "",
                Dian_H = t.Dian_H ,
                OrderNo = t.OrderNo,
                Chao_BYDM = t.Chao_BYDM

            }).OrderBy(t => t.id).Skip(param.iDisplayStart).Take(param.iDisplayLength).ToList();

            int sortId = param.iDisplayStart + 1;

            var result = from c in filterResult
                         select new[]
                        {
                            sortId++.ToString(), 
                            c.Chao_BYMC,
                            c.CompanyName,
                            c.Chao_BYDM,
                            c.Dian_H,
                            c.OrderNo.ToString(),
                            c.id.ToString()
                        };

            return Json(new
            {
                sEcho = param.sEcho,
                iDisplayStart = param.iDisplayStart,
                iTotalRecords = total,
                iTotalDisplayRecords = total,
                aaData = result
            }, JsonRequestBehavior.AllowGet);
        }

        public ActionResult Create()
        {
            var model = new MeterReaderModel();
            InitMeterReaderModel(model);
            return PartialView(model);
        }

        [HttpPost]
        [AdminOperateLog]
        public ActionResult Create(MeterReaderModel model)
        {
            if (ModelState.IsValid)
            {
                OperationResult result = MeterReaderService.Insert(model);
                if (result.ResultType == OperationResultType.Success)
                {
                    return Json(result);
                }
                else
                {
                    return PartialView(model);
                }
            }
            else
            {
                return PartialView(model);
            }
        }

        public ActionResult Edit(int Id)
        {
            var model = new MeterReaderModel();
            var entity = MeterReaderService.MeterReaders.FirstOrDefault(t => t.Id == Id);
            if (null != entity)
            {
                model = new MeterReaderModel
                {
                    id = entity.Id,
                    Chao_BYMC =entity.Chao_BYMC,
                    Chao_BYDM = entity.Chao_BYDM,
                    Dian_H = entity.Dian_H,
                    CompanyId=entity.Dan_WSZ_No,
                    OrderNo = entity.OrderNo


                };
            }

            InitMeterReaderModel(model);
            return PartialView(model);
        }

        [HttpPost]
        public ActionResult Edit(MeterReaderModel model)
        {
            InitMeterReaderModel(model);
            if (ModelState.IsValid)
            {
                OperationResult result = MeterReaderService.Update(model);
                if (result.ResultType == OperationResultType.Success)
                {
                    return Json(result);
                }
                else
                {
                    return PartialView(model);
                }

            }
            else
            {
                return PartialView(model);
            }
            
        }


        public ActionResult Delete(int Id)
        {
            OperationResult result = MeterReaderService.Delete(Id);
            return Json(result);
        }


        private Expression<Func<MeterReader, Boolean>> BuildSearchCriteria()
        {
            DynamicLambda<MeterReader> bulider = new DynamicLambda<MeterReader>();
            Expression<Func<MeterReader, Boolean>> expr = null;
            if (!string.IsNullOrEmpty(Request["Chao_BYMC"]))
            {
                var data = Request["Chao_BYMC"].Trim();
                Expression<Func<MeterReader, Boolean>> tmp = t => t.Chao_BYMC.Contains(data);
                expr = bulider.BuildQueryAnd(expr, tmp);
            }
            if (!string.IsNullOrEmpty(Request["Dian_H"]))
            {
                var data = Request["Dian_H"].Trim();
                Expression<Func<MeterReader, Boolean>> tmp = t => t.Dian_H.Contains(data);
                expr = bulider.BuildQueryAnd(expr, tmp);
            }
            if (!string.IsNullOrEmpty(Request["Chao_BYDM"]) && Request["Chao_BYDM"] != "0")
            {
                var data = Request["Chao_BYDM"].Trim();
                Expression<Func<MeterReader, Boolean>> tmp = t => t.Chao_BYDM.ToString().Contains(data);
                expr = bulider.BuildQueryAnd(expr, tmp);
            }
            if (!string.IsNullOrEmpty(Request["Dan_WSZ_No"]) && Request["Dan_WSZ_No"] != "0")
            {
                var data = Convert.ToInt32(Request["Dan_WSZ_No"]);
                Expression<Func<MeterReader, Boolean>> tmp = t => (t.Id == data) || (t.Dan_WSZ_No == data);
                expr = bulider.BuildQueryAnd(expr, tmp);
            }


            Expression<Func<MeterReader, Boolean>> tmpSolid = t => t.IsDeleted == false;
            expr = bulider.BuildQueryAnd(expr, tmpSolid);

            return expr;
        }


        private void InitMeterReaderModel(MeterReaderModel model)
        {
            #region 单位信息
            var parentModuleData = CompanySetService.CompanySets.Where(t => t.IsDeleted == false)
            .Select(t => new MeterReaderModel
            {
                CompanyId = t.Id,
                CompanyName = t.Dan_WMC
            });
            foreach (var item in parentModuleData)
            {
                model.CompanyItems.Add(new SelectListItem { Text = item.CompanyName, Value = item.CompanyId.ToString() });
            }
            #endregion


           
        }
    }
}
